package com.ruoyi.framework.config;

import com.ruoyi.common.config.OkHttpConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * OkHttp客户端配置
 *
 * @author ruoyi
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class OkHttpClientConfig {
    
    private final OkHttpConfig okHttpConfig;
    
    /**
     * 配置OkHttp客户端
     *
     * @return OkHttpClient实例
     */
    @Bean
    public OkHttpClient okHttpClient() {
        // 配置连接池
        ConnectionPool connectionPool = new ConnectionPool(
                okHttpConfig.getMaxIdleConnections(),
                okHttpConfig.getKeepAliveDuration(),
                TimeUnit.MINUTES
        );
        
        // 配置调度器
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(okHttpConfig.getMaxRequests());
        dispatcher.setMaxRequestsPerHost(okHttpConfig.getMaxRequestsPerHost());
        
        // 构建OkHttp客户端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(Duration.ofSeconds(okHttpConfig.getConnectTimeout()))
                .readTimeout(Duration.ofSeconds(okHttpConfig.getReadTimeout()))
                .writeTimeout(Duration.ofSeconds(okHttpConfig.getWriteTimeout()))
                .connectionPool(connectionPool)
                .dispatcher(dispatcher)
                .retryOnConnectionFailure(okHttpConfig.isRetryOnConnectionFailure())
                .build();
        
        log.info("OkHttp客户端配置完成 - 连接超时:{}s, 读取超时:{}s, 写入超时:{}s, 最大连接数:{}", 
                okHttpConfig.getConnectTimeout(),
                okHttpConfig.getReadTimeout(), 
                okHttpConfig.getWriteTimeout(),
                okHttpConfig.getMaxIdleConnections());
        
        return client;
    }
}
